import axios from "axios";
import store from "@/store";
import router from "@/router";
import { Toast } from "vant";

const instance = axios.create({
    baseURL: "/admin",
    timeout: 15 * 1000,
    withCredentials: true
});

// 请求拦截
instance.interceptors.request.use(
    config => {
        // 请求头添加token
        if (store.getters.access_token) {
            config.headers.Authorization = `Bearer ${store.getters.access_token}`;
            config.headers.Login_type = "0";
        } else {
            config.headers = {
                Accept: "application/json, text/plain, */*",
                isToken: false,
                TENANT_ID: "1",
                Authorization: "Basic ZGNwbXM6ZGNwbXM=",
                Login_type: "0"
            };
            if (config.header) {
                config.headers.Authorization = "Basic dGVzdDp0ZXN0";
            }
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// 返回拦截
instance.interceptors.response.use(
    response => {
        // 接口返回状态码处理
        if (response.status === 200) {
            const data = response.data;
            switch (data.code) {
                case 0:
                    return response;
                case 1:
                    Toast.fail(data.msg || "接口异常");
                    break;
                case 2:
                    Toast.fail("登录超时，请重新登录");
                    setTimeout(() => {
                        router.push("/");
                    }, 500);
                    break;
                default:
                    if (data.msg) {
                        Toast.fail(data.msg);
                    }
                    return response;
            }
            return Promise.reject(response);
        }
    },
    error => {
        // 请求报错处理
        if (error.response) {
            const status = error.response.status;
            switch (status) {
                case 401:
                    store.commit("SET_ACCESS_TOKEN", null);
                    store.commit("SET_AWS_TOKEN", null);
                    Toast.fail("没有权限，请重新登录");
                    setTimeout(() => {
                        router.push("/");
                    }, 500);
                    break;
                case 404:
                    Toast.fail("你所访问的页面不存在");
                    break;
                case 500:
                    Toast.fail("连接服务失败");
                    break;
                case 503:
                case 504:
                    Toast.fail("啊哦~ 连接服务器失败,请稍后重试");
                    break;
                default:
                    return Promise.reject(error);
            }
        }
        return Promise.reject((error.response && error.response.data) || error);
    }
);

export default instance;